package org.jeecg.basic.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.jeffreyning.mybatisplus.service.MppServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.jeecg.basic.entity.MesBomItemSetup;
import org.jeecg.basic.mapper.MesBomItemSetupMapper;
import org.jeecg.basic.service.IMesBomItemSetupService;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description: 产品BOM
 * @Author: LiCY
 * @Date: 2023-06-16
 * @Version: V1.0
 */
@Service
@Slf4j
public class MesBomItemSetupServiceImpl extends MppServiceImpl<MesBomItemSetupMapper, MesBomItemSetup> implements IMesBomItemSetupService {

    @Autowired
    private MesBomItemSetupMapper mesBomItemSetupMapper;

    @Autowired
    private CommonAPI commonAPI;

    @Override
    public List<MesBomItemSetup> selectByMainId(String mainId) {
        return mesBomItemSetupMapper.selectByMainId(mainId);
    }

    @Override
    public void getImportMould(HttpServletResponse response) {
        //定义easyExcel导出的对象
        ExcelWriter excelWriter = null;
        WriteCellStyle exportExcelStyle = commonAPI.getExportExcelStyle();
        //头策略使用默认 设置字体大小
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short) 10);
        headWriteCellStyle.setWriteFont(headWriteFont);
        try {
            excelWriter = EasyExcel.write(response.getOutputStream()).build();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=demo.xlsx");
            ExcelWriterSheetBuilder materialScrap = EasyExcel.writerSheet(0, "产品BOM");
            materialScrap.head(MesBomItemSetup.class)
                    .registerWriteHandler(new HorizontalCellStyleStrategy(headWriteCellStyle, exportExcelStyle));
            //查询数据并写入
            List<MesBomItemSetup> list = new ArrayList<>();
            excelWriter.write(list, materialScrap.build());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }

    @Override
    public Result<?> importMesBomItemSetup(HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            try {
                InputStream inputStream = file.getInputStream();
                List<MesBomItemSetup> list = EasyExcel.read(inputStream) //调用read方法
                        //注册自定义监听器，字段校验可以在监听器内实现
                        .head(MesBomItemSetup.class) //对应导入的实体类
                        .sheet(0) //导入数据的sheet页编号，0代表第一个sheet页，如果不填，则会导入所有sheet页的数据
                        .headRowNumber(1) //列表头行数，1代表列表头有1行，第二行开始为数据行
                        .doReadSync(); //开始读Excel，返回一个List<T>集合，继续后续入库操作
                long start = System.currentTimeMillis();
                this.saveBatch(list);
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                return Result.OK("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    @Override
    public void exportImportMould(HttpServletRequest request, HttpServletResponse response, Map<String, Object> param) {
        //定义easyExcel导出的对象
        ExcelWriter excelWriter = null;
        //内容样式策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        //垂直居中,水平居中
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
        contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
        contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
        contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
        // 字体策略
        WriteFont contentWriteFont = new WriteFont();
        // 字体大小
        contentWriteFont.setFontHeightInPoints((short) 8);
        contentWriteCellStyle.setWriteFont(contentWriteFont);
        //头策略使用默认 设置字体大小
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short) 10);
        headWriteCellStyle.setWriteFont(headWriteFont);
        try {
            excelWriter = EasyExcel.write(response.getOutputStream()).build();
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=demo.xlsx");
            ExcelWriterSheetBuilder procHistory = EasyExcel.writerSheet(0, "产品BOM模板");
            procHistory.head(MesBomItemSetup.class)
                    .registerWriteHandler(new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle));
            //查询数据并写入
            QueryWrapper<MesBomItemSetup> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("PARTNO",param.get("partno"));
            excelWriter.write(this.list(queryWrapper), procHistory.build());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }
}
